<template>
  <div>
    <div style="display: flex;justify-content: center">
      <el-input
        placeholder="通過用戶名搜索用戶..."
        prefix-icon="el-icon-search"
        style="width: 500px;margin-right: 10px"
        v-model="keyword"
        @keydown.enter.native="getAdminByKw"
      ></el-input>
      <el-button type="primary" icon="el-icon-search" @click="getAdminByKw">搜索</el-button>
      <el-button type="primary" icon="el-icon-circle-plus-outline" @click="createAdmin">新增用户</el-button>
    </div>
    <div class="admin-content">
      <el-card
        class="admin-card"
        v-for="(admin,index) in admins"
        :key="index"
      >
        <div slot="header" class="clearfix">
          <span>{{ admin.name }}</span>
          <el-button
            style="float: right; padding: 3px 0;color: red"
            type="text"
            icon="el-icon-delete"
            @click="deleteAdmin(admin)"
          >
          </el-button>
        </div>
        <div>
          <div class="img-container">
            <img :src="admin.userFace" :alt="admin.name" :title="admin.name" class="userface-img">
          </div>
        </div>
        <div class="userinfo-container">
          <div style="margin-bottom: 20px;margin-top:10px;display: flex;justify-content: center">
            <el-tag style="margin-right: 4px" type="success" v-for="(role,indexj) in admin.roles" :key="indexj">
              {{role.nameZh}}
            </el-tag>
            <el-popover
              placement="right"
              title="角色列表"
              width="200"
              trigger="click"
              @show="showRole(admin)"
              @hide = "hideHandle(admin)"
            >
              <el-select
                v-model="selectRoleArr"
                multiple
                placeholder="請選擇"
              >
                <el-option
                  v-for="(r,index) in allRoles"
                  :key="index"
                  :label="r.nameZh"
                  :value="r.id"
                ></el-option>
              </el-select>
              <el-button slot="reference" type="text" icon="el-icon-more" style="color: #d1dbe5"></el-button>
            </el-popover>
          </div>
          <div>用户名：{{admin.username}}</div>
          <div>姓名：{{admin.name}}</div>
          <div>手机号码：{{admin.phone}}</div>
<!--          <div>电话号码：{{admin.telephone}}</div>-->
          <div v-show="admin.remark !== null">备注：{{admin.remark}}</div>
          <div>地址：{{admin.address}}</div>
          <div style="margin-top: 20px">用户状态：
            <el-switch
                v-model="admin.enabled"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="enabledChange(admin)"
            ></el-switch>
          </div>
        </div>

      </el-card>
    </div>
    <div>
      <el-dialog
        append-to-body
        title="添加用户"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="dialogVisible = false">
        <div>
          <el-form  :model="creteForm" :rules="rules" ref="ruleForm">
            <el-form-item prop="workId">
              <el-input type="text" auto-complete="false"  v-model="creteForm.workId" placeholder="请输入员工号"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="doCreateAdmin('ruleForm')">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import adminAPI from "@/api/admin";
export default {
  name: "SysAdmin",
  data(){
    return{
      admins:[],// 操作员列表
      keyword:'',// 搜索关键词
      allRoles:'',
      selectRoleArr:[],
      creteForm:{
        workId:'',
      },

      dialogVisible:false,
      rules: {
        workId :[{ required: true, message: '请输入员工号', trigger: 'blur' }]
      },
    }
  },
  methods:{
    // 調用更新操作員接口
    updateAdminRole(admin){
      adminAPI.updateAdminRoles(admin.id,this.selectRoleArr).then(res => {
        if (res) {
          this.initAdmins();
        }
      })
    },
    hideHandle(admin){
      // 是否要更新操作員角色標識
      let flag = true;
      let roles = [];
      let selectRole = this.selectRoleArr; // 已經選擇的角色id數組
    //  Object.assign(roles,admin.roles); // 拷貝已擁有的角色對象
      // 對比選中的是否與已擁有的角色對象相同
      admin.roles.forEach((item,index) => {
        roles.push(item.id);
        // this.selectRoleArr.remove()
      })
      //   排序後轉化為對象比較 如果相同則代表橘色數組沒改變 則不調用接口更新
      if (JSON.stringify(roles.sort()) === JSON.stringify(selectRole.sort())){
        console.log("數組相同");
        flag = false; // 數組相同 不更新
      }
      // 如果選擇數組發生改變才更新
      if (flag){
        this.updateAdminRole(admin); // 更新操作員角色
      }

    },
    showRole(admin){
      this.initAllRoles();
      // 初始化已有角色標籤
      let roles = admin.roles; // 對象
      this.selectRoleArr = [];
      roles.forEach(r => {
        this.selectRoleArr.push(r.id);
      })
    },
    initAllRoles(){
      adminAPI.getAllRoles().then(res => {
        if (res){
          this.allRoles = res.data;
        }
      })
    },
    initAdmins(){
      adminAPI.getAllAdmins(this.keyword).then(res => {
        if (res){
          this.admins = res.data;
          console.log(res);
        }
      })
    },
    getAdminByKw(){
      this.initAdmins();
    },
    deleteAdmin(admin){
      this.$confirm('此操作将永久删除['+ admin.name +']操作员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除操作
        adminAPI.deleteAdmin(admin.id).then(res => {
          if (res){
            console.log("删除操作员结果");
            console.log(res);
            this.initAdmins(); // 刷新操作员信息
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    enabledChange(admin){
      adminAPI.updateAdmin(admin).then(res => {
        if (res){
          console.log("更新操作员结果");
          console.log(res);
          this.initAdmins();
          if (admin.enabled === false){
            this.$message.success("禁用操作员成功！")
          }else{
            this.$message.success("启用操作员成功！")
          }
        }
      })
    },
    createAdmin(){
      this.dialogVisible = true;
    },
    doCreateAdmin(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = new FormData();
          params.append('workId',this.creteForm.workId)
          adminAPI.createAdmin(params).then(res => {
            if (res){
              this.initAdmins()
              this.dialogVisible = false;
              this.creteForm.workId = ''
            }
          })
        }else {
          return false;
        }
      })

    }
  },
  mounted() {
    this.initAdmins();
  },
  watch: {
    // 监听搜索框 如果值被清空则重新获取操作员
    keyword(val){
      if (val === ''){
        this.initAdmins();
      }
    }

  }
}
</script>

<style scoped>
  .admin-content{
    flex-wrap: wrap;
    justify-content: space-around;
    display: flex;
    margin-bottom: 20px;
  }
  .admin-card{
    width: 350px;
    margin-top: 30px;
  }
  .userface-img{
    width: 72px;
    height: 72px;
    border-radius: 72px;
  }
  .img-container{
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .userinfo-container{
    font-size: 12px;
  }

</style>
